package com.fuyao.cloud.admin.flow.actor;

import cn.hutool.core.lang.ClassScanner;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class HandlerProcessor implements BeanFactoryPostProcessor {

    private static final String HANDLER_PACKAGE = "com.fuyao.cloud.admin.flow.actor";

    /**
     * 扫描@HandlerType,初始化HandlerContext,将其注册到spring容器
     *
     * @param beanFactory bean工厂
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        log.info("HandlerType init beanFactor");
        Map<String, Class> handlerMap = Maps.newLinkedHashMapWithExpectedSize(4);
        ClassScanner.scanPackageByAnnotation(HANDLER_PACKAGE, ActorTypeCodeAnnotation.class).forEach(clazz -> {
            // 获取注解中的类型值
            String type = clazz.getAnnotation(ActorTypeCodeAnnotation.class).value();
            // 将注解中的类型作为Key,对应的类作为value,保存到Map中
            handlerMap.put(type, clazz);
        });
        // 初始化HandlerContext，将其注册到spring容器
        HandlerContext context = new HandlerContext(handlerMap);
        beanFactory.registerSingleton(HandlerContext.class.getName(), context);
    }
}
